// pages/index/storeselect/index.js
const util = require("../../../utils/util");
import Toast from "../../../vant/weapp/toast/toast";
const app = getApp()
let times = util.formatTimeHour(new Date()).split(":")
let hourList = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]
let fenList = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59"]
let hour = hourList.slice(times[0])
let sencend = fenList.slice(times[1])
let arr = {}
let keyMap = {}
let obj = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    clicktime: 1,
    dayList: [],
    chooseIndex: 0,
    package_id: 0,
    packageList: [],
    pagIndex: 0,
    multiArray: [{
        values: Object.keys(obj),
        className: 'column1',
      },
      {
        values: obj[hour[0]],
        className: 'column2',
        // defaultIndex: 2,
      },
    ],
    pick_show_start: false,
    pick_hour_show_start: false,
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      }
      return `${value}日`;
    },
    currentDate_start: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date(new Date().setDate(new Date().getDate() + 6)).getTime(),
    id: 0,
    timeList: [],
    timeList1: [],
    timeListN: "",
    timeListN1: "",
    safeAreaInsets: 0,
    shijian: "上午"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

    const that = this
    let dayList = util.dateListGet(new Date())

    times = util.addMin(new Date()).split(":")
    hour = hourList.slice(times[0])
    sencend = fenList.slice(times[1])
    arr = []
    arr[0] = sencend
    keyMap[0] = hour[0]
    for (let i = 1; i < hour.length; i++) {
      arr[i] = fenList
      keyMap[i] = hour[i]
    }
    obj = Object.keys(arr).reduce((newData, key) => {
      let newKey = keyMap[key]
      newData[newKey] = arr[key]
      return newData
    }, {})
    that.setData({
      dayList,
      multiArray: [{
          values: Object.keys(obj),
          className: 'column1',
        },
        {
          values: obj[hour[0]],
          className: 'column2',
          // defaultIndex: 2,
        },
      ],
      date_start: util.formatTimeDay(new Date()),
      time_start: util.addMin(new Date()), //开始
      date_end: util.formatTimeDay(new Date()),
      time_end: util.formatTimeHour(new Date()),
      store_id: options.store_id,
      room_id: options.room_id,
      start_index: '',
      safeAreaInsets: app.globalData.safeAreaInsets
    })
  },

  onShow() {
    const that = this
    that.getPackageCourseTime(that.data.room_id)
  },

  // 更改时间
  time(e) {
    const that = this
    // let start_time = that.data.multiArray[0][that.data.multiIndex[0]] + ':' + that.data.multiArray[1][that.data.multiIndex[1]]
    let now_time = that.data.date_start + " " + that.data.time_start;
    let next_time = new Date(now_time.replace(/\-/g, "/")).setHours(
      new Date(now_time.replace(/\-/g, "/")).getHours() + that.data.time
    );
    let start = that.data.time_start.replace(/\:/g, "")
    let start_index
    if (start[0] == 0) {
      start_index = start[1]
    } else {
      start_index = start[0] + start[1]
    }
    let time_end = util.formatH(next_time);
    let date_end = util.formatDate(next_time);
    let time = new Date(now_time.replace(/\-/g, "/"))
    if (util.formatTimeDay(time) != util.formatTimeDay(new Date()) && e != "end") {
      for (let i = 0; i < hourList.length; i++) {
        obj[i] = fenList
      }
      that.setData({
        multiArray: [{
            values: Object.keys(obj),
            className: 'column1',
          },
          {
            values: obj[hourList[0]],
            className: 'column2',
            // defaultIndex: 2,
          },
        ],
      })
    } else {
      arr[0] = sencend
      keyMap[0] = hour[0]
      for (let i = 1; i < hour.length; i++) {
        arr[i] = fenList
        keyMap[i] = hour[i]
      }
      obj = Object.keys(arr).reduce((newData, key) => {
        let newKey = keyMap[key]
        newData[newKey] = arr[key]
        return newData
      }, {})
      that.setData({
        multiArray: [{
            values: Object.keys(obj),
            className: 'column1',
          },
          {
            values: obj[hour[0]],
            className: 'column2',
            // defaultIndex: 2,
          },
        ]
      })
    }
    that.setData({
      time_end,
      date_end,
      start_index
    })
  },
  onClose() {
    this.setData({
      pick_show_start: false,
      pick_hour_show_start: false,
    });
  },
  getPackageCourseTime(room_id) {
    const that = this
    app.http.post(app.api.PackageCourseTime, {
      room_id
    }, (res) => {

      if (res.data.end_time == 0) {
        that.setData({
          packageList: res.data.package,
          time: res.data.package[0].time,
          package_id: res.data.package[0].package_id,
        })
      } else {
        that.setData({
          packageList: res.data.package,
          time: res.data.package[0].time,
          package_id: res.data.package[0].package_id,
          time_start: util.addMin(new Date(res.data.end_time.replace(/\-/g, "/"))),
          date_start: util.formatDate(new Date(res.data.end_time.replace(/\-/g, "/")))
        })

      }

      that.getPackageCourse(res.data.package[0].package_id)
      that.time()
    })
  },
  //   日期选择器
  bindDateChange: function (e) {
    const that = this
    if (util.formatTimeDay(new Date(e.detail)) != util.formatTimeDay(new Date())) {
      for (let i = 0; i < hourList.length; i++) {
        obj[i] = fenList
      }
      that.setData({
        date_start: util.formatTimeDay(new Date(e.detail)),
        multiArray: [{
            values: Object.keys(obj),
            className: 'column1',
          },
          {
            values: obj[hourList[0]],
            className: 'column2',
            // defaultIndex: 2,
          },
        ],
        time_start: "00:00"
      })
    } else {
      arr[0] = sencend
      keyMap[0] = hour[0]
      for (let i = 1; i < hour.length; i++) {

        arr[i] = fenList

        keyMap[i] = hour[i]
      }
      obj = Object.keys(arr).reduce((newData, key) => {
        let newKey = keyMap[key]
        newData[newKey] = arr[key]
        return newData
      }, {})
      that.setData({
        date_start: util.formatTimeDay(new Date(e.detail)),
        multiArray: [{
            values: Object.keys(obj),
            className: 'column1',
          },
          {
            values: obj[hour[0]],
            className: 'column2',
          },
        ],
        time_start: util.addMin(new Date())
      })
    }

    for (let i = 0; i < that.data.dayList.length; i++) {
      if (util.formatTimeDay(new Date(e.detail)) == util.formatTimeDay(new Date(that.data.dayList[i].day))) {
        that.setData({
          chooseIndex: i
        })
      }
    }

    that.time()
    that.onClose()
    that.getPackageCourse(that.data.package_id)
  },
  // 选择时间
  bindChange(e) {
    const that = this
    let index = e.detail.value[0]
    if (e.detail.value[0] < 10) {
      e.detail.value[0] = "0" + e.detail.value[0]
    }
    let time_start = e.detail.value[0] + ":" + e.detail.value[1]

    that.setData({
      pick_hour_show_start: false,
      time_start,
      start_index: index
    })
    that.getPackageCourse(that.data.package_id)
    that.time()
  },
  onChange(e) {
    const that = this
    console.log(e)
    const {
      picker,
      value,
      index
    } = e.detail;
    if (value[0] >= 12) {
      that.setData({
        shijian: "下午"
      })
    } else {
      that.setData({
        shijian: "上午"
      })
    }
    picker.setColumnValues(1, obj[value[0]]);
  },
  // 日期选择唤起
  select_pick_start(e) {
    this.setData({
      pick_show_start: true,
    });
  },
  //时间选择唤起
  select_hour_start() {
    let hourTim = this.data.time_start.split(":")
    if (hourTim[0] >= 12) {
      this.setData({
        shijian: "下午",
        pick_hour_show_start: true,
      })
    } else {
      this.setData({
        shijian: "上午",
        pick_hour_show_start: true,
      })
    }
  },
  // 套餐选择
  choosePage(e) {
    const that = this
    that.setData({
      clicktime: 1,
      rank: e.currentTarget.dataset.rank,
    })

    if (e.currentTarget.dataset.rank == 1) {
      if (util.formatHt(new Date()) > 1) {
        that.setData({
          clicktime: 0,
          chooseIndex: 1,
          date_start: util.formatTimeDay(new Date(Date.parse(new Date()) + 3600 * 24 * 1000)),
          time_start: util.addMin(new Date(util.formatTimeDay(new Date(Date.parse(new Date()) + 3600 * 24 * 1000)) + ' 00:57:00')), //开始
        })


      } else {
        that.setData({
          clicktime: 0,
          date_start: util.formatTimeDay(new Date(Date.parse(new Date()))),
          time_start: util.addMin(new Date(util.formatTimeDay(new Date(Date.parse(new Date()) + 3600 * 24 * 1000)) + ' 00:57:00')), //开始
        })
      }

    }
    that.setData({


      pagIndex: e.currentTarget.dataset.index,
      time: e.currentTarget.dataset.time,
      package_id: e.currentTarget.dataset.id
    })
    that.getPackageCourse(e.currentTarget.dataset.id)
    that.time()
  },
  // 获取套餐
  getPackageCourse(id) {
    console.log(id)
    const that = this
    let add_time = that.data.date_start + " " + that.data.time_start;
    app.http.post(app.api.PackageCourse, {
      room_id: that.data.room_id,
      package_id: that.data.id,
      add_time,
      package_id: id
    }, (res) => {
      let nums = that.data.time
      let index, date_start, chooseIndex
      if (res.data.end_time != 0) {
        arr = []
        times = util.addMin(new Date(res.data.end_time.replace(/\-/g, "/"))).split(":")
        console.log(times)
        hour = hourList.slice(times[0])
        sencend = fenList.slice(times[1])
        arr[0] = sencend
        keyMap[0] = hour[0]
        for (let i = 1; i < hour.length; i++) {
          arr[i] = fenList
          keyMap[i] = hour[i]
        }
        obj = Object.keys(arr).reduce((newData, key) => {
          let newKey = keyMap[key]
          newData[newKey] = arr[key]
          return newData
        }, {})
        if (new Date(add_time.replace(/\-/g, "/")) < new Date(res.data.end_time.replace(/\-/g, "/"))) {
          that.setData({
            time_start: util.addMin(new Date(res.data.end_time.replace(/\-/g, "/"))),
            multiArray: [{
                values: Object.keys(obj),
                className: 'column1',
              },
              {
                values: obj[hour[0]],
                className: 'column2',
                // defaultIndex: 2,
              },
            ],
          })
        } else {
          that.setData({
            multiArray: [{
                values: Object.keys(obj),
                className: 'column1',
              },
              {
                values: obj[hour[0]],
                className: 'column2',
                // defaultIndex: 2,
              },
            ],
          })
        }
        if (new Date(add_time.replace(/\-/g, "/")) < new Date(res.data.end_time.replace(/\-/g, "/"))) {
          date_start = util.formatTimeDay(new Date(res.data.end_time.replace(/\-/g, "/")))
          chooseIndex = Math.floor(Math.abs(new Date(date_start.replace(/\-/g, "/")).getTime() - new Date(util.formatDates(new Date())).getTime()) / (24 * 3600 * 1000))
          that.setData({
            date_start,
            time_start: util.addMin(new Date(res.data.end_time.replace(/\-/g, "/"))),
            chooseIndex,
          })

          that.time("end")
        }

      }

      if (that.data.start_index != 0) {
        index = Number(that.data.start_index)
      } else {
        index = 0
      }
      for (let i = index; i < 24; i++) {
        if (nums <= 0) {
          break
        }
        let a = Number(i) + 1
        if (a == 24) {
          a = 23
        }
        if (res.data.time[i].status == 0) {
          console
          res.data.time[i].status = 2
          nums--
          // let a = Number(i) + 1
          // if (a == 24) {
          //     a = 23
          // }
          if (nums <= 0) {
            break
          } else if (nums > 0 && res.data.time[a].status != 0) {
            for (let i = 0; i < res.data.time.length; i++) {
              if (res.data.time1[i].status == 0) {
                res.data.time1[i].status = 2
                nums--
                if (nums <= 0) {
                  break
                }
              }
            }
          }
        } else if (res.data.time[a].status != 0) {
          for (let i = 0; i < res.data.time1.length; i++) {
            if (res.data.time1[i].status == 0) {
              res.data.time1[i].status = 2
              nums--
              if (nums <= 1) {
                break
              }
            }
          }

        }
      }
      that.setData({
        end_time: res.data.end_time,
        timeList: res.data.time,
        timeList1: res.data.time1,
        timeListN: util.formatTimeDay(new Date(res.data.time[0].add_time * 1000)),
        timeListN1: util.formatTimeDay(new Date(res.data.time1[0].add_time * 1000))
      })
    })
  },
  // 选择日期
  chooseTime(e) {
    const that = this
    let index = e.currentTarget.dataset.index
    let time = new Date(new Date().setDate(new Date().getDate() + index))
    let date_start = util.formatTimeDay(time)
    if (util.formatTimeDay(time) != util.formatTimeDay(new Date())) {
      for (let i = 0; i < hourList.length; i++) {
        obj[i] = fenList
      }
      that.setData({
        multiArray: [{
            values: Object.keys(obj),
            className: 'column1',
          },
          {
            values: obj[hourList[0]],
            className: 'column2',
            // defaultIndex: 2,
          },
        ],
        time_start: that.data.rank == 1 ? '01:00' : '00:00'
      })

    } else {

      if (that.data.rank == 1 && util.formatHt(new Date()) > 1) {
        return
      }
      arr[0] = sencend
      keyMap[0] = hour[0]
      for (let i = 1; i < hour.length; i++) {

        arr[i] = fenList

        keyMap[i] = hour[i]
      }
      obj = Object.keys(arr).reduce((newData, key) => {
        let newKey = keyMap[key]
        newData[newKey] = arr[key]
        return newData
      }, {})

      that.setData({

        time_start: that.data.rank == 1 ? '01:00' : util.addMin(new Date()),
        multiArray: [{
            values: Object.keys(obj),
            className: 'column1',
          },
          {
            values: obj[hour[0]],
            className: 'column2',
            // defaultIndex: 2,
          },
        ]
      })
    }
    that.setData({
      chooseIndex: e.currentTarget.dataset.index,
      date_start
    })
    that.time()
    that.getPackageCourse(that.data.package_id)
    // that.getroomlist()
  },
  toOrder() {
    const that = this
    let add_time = that.data.date_start + " " + that.data.time_start;
    let end_time = that.data.date_end + " " + that.data.time_end;
    app.http.post(app.api.makeOrder, {
      store_id: that.data.store_id,
      room_id: that.data.room_id,
      add_time,
      end_time,
      package_id: that.data.package_id
    }, (res) => {
      if (res.code !== 200) {
        Toast.fail(res.msg)
      } else {
        wx.navigateTo({
          url: "/pages/index/order/index?store_id=" + res.data.data.store_id + "&order_on=" + res.data.data.order_on,
        });
      }
    })
  },
  onShareAppMessage() {

  }
})